package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.entity.to.es.SkuESModel;
import com.atguigu.gulimall.search.config.GulimallSearchConfig;
import com.atguigu.gulimall.search.constant.ESConstant;
import com.atguigu.gulimall.search.service.ProductSearchSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSearchSaveServiceImpl implements ProductSearchSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean saveProduct(List<SkuESModel> eSModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel eSModel : eSModels) {
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            indexRequest.id(eSModel.getSkuId().toString());


            String s = JSON.toJSONString(eSModel);

            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallSearchConfig.COMMON_OPTIONS);

        boolean b = !bulk.hasFailures();
        List<Object> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        log.info("商品上架完成，{}",collect);

        return b;
    }
}
